/*
 * Copyright 2018 dc-square GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.hivemq.extensions.rbac.configuration;

import com.hivemq.extensions.rbac.configuration.entities.ExtensionConfig;
import com.hivemq.extensions.rbac.configuration.entities.FileAuthConfig;
import com.hivemq.extensions.rbac.configuration.entities.User;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.extension.sdk.api.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;


/**
 * Xml 解析器
 */
@ThreadSafe
public class XmlParser {

    private static final Logger log = LoggerFactory.getLogger(XmlParser.class);

    //jaxb上下文是线程安全的
    private final @NotNull JAXBContext jaxb;

    public XmlParser() {
        try {
            jaxb = JAXBContext.newInstance(FileAuthConfig.class, User.class, ExtensionConfig.class);
        } catch (JAXBException e) {
            log.error("文件验证扩展名中的错误。无法初始化XML解析器", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 将配置编组到XML文件。
     * <p>
     * 该文件不能存在，否则此方法将失败
     *
     * @param config 写入XML的配置
     * @param file   XML应该写入的文件
     * @throws NotMarshallableException 如果无法将XML编组
     */
    public void marshal(@NotNull final FileAuthConfig config, @NotNull final File file) throws NotMarshallableException {

        if (file.isDirectory()) {
            throw new NotMarshallableException("无法将配置写入文件 " + file.getAbsolutePath() + " 因为它是一个目录");
        }

        if (file.exists()) {
            throw new NotMarshallableException("文件 " + file.getAbsolutePath() + " 已经存在");
        }

        if (file.canWrite()) {
            throw new NotMarshallableException("无法将配置写入文件 " + file.getAbsolutePath() + " 因为它不可写");
        }

        try {
            final Marshaller marshaller = jaxb.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(config, file);
        } catch (JAXBException e) {
            throw new NotMarshallableException("无法将配置写入文件 " + file.getAbsolutePath(), e);

        }

    }

    @NotNull
    public FileAuthConfig unmarshalFileAuthConfig(@NotNull final File file) throws IOException {

        try {
            final Unmarshaller unmarshaller = jaxb.createUnmarshaller();
            return (FileAuthConfig) unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            throw new IOException(e);
        }

    }

    @NotNull
    public ExtensionConfig unmarshalExtensionConfig(@NotNull final File file) throws IOException {

        try {
            final Unmarshaller unmarshaller = jaxb.createUnmarshaller();
            return (ExtensionConfig) unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            throw new IOException(e);
        }

    }

}
